package self.xine.basic.thread.entity;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyQueue<T> {
	private Lock myLock = new ReentrantLock();
	private Condition notEmpty = myLock.newCondition();
	private Condition notFull = myLock.newCondition();
	
	private Object[] elements;
	private int length = 0,addIndex = 0, removeIndex = 0;
	
	public MyQueue(int size) {
		if(size < 1) {
			size = 1;
		}		
		elements = new Object[size];
	}
	
	public void add(T object) throws InterruptedException {
		myLock.lock();
		try {
			while(elements.length == length) {				
				System.out.println("队列已满，请等待被取出");
				notFull.await();				
			}
			
			elements[addIndex] = object;
			addIndex++;			
			if(addIndex == elements.length) {
				addIndex = 0;
			}
			
			length++;
			
			System.out.println(Thread.currentThread().getName() + " : " + length + "\t " + object);
	
			notEmpty.signalAll();			
		}
		finally {
			myLock.unlock();
		}
	}
	
	@SuppressWarnings("unchecked")
	public T remove() throws InterruptedException {
		myLock.lock();
		try {
			while(length == 0) {				
				System.out.println("队列为空，请等待被存放");
				notEmpty.await();				
			}
			
			Object object = elements[removeIndex];
			removeIndex++;			
			if(removeIndex == elements.length) {
				removeIndex = 0;
			}
			
			length--;
			
			System.out.println(Thread.currentThread().getName() + " : " + length + "\t " + object);
			
			notFull.signalAll();
			return (T)object;
		}finally {
			myLock.unlock();
		}
		
	}
	
	public int length() {
		return length;
	}

}
